<?php

declare(strict_types=1);

namespace App\CustHub\Policies;

use App\CustHub\Constants\ChRoleDataScopeTypeConstants;
use App\CustHub\Mapper\ChUserMapper;
use Hyperf\Database\Model\Builder;

class ChUserPolicy
{
    public function apply(Builder $builder, ?int $uid = null,string $tableName = '')
    {

        $uid = is_null($uid) ? chUser()->getId() : $uid;


        $user = container()->get(ChUserMapper::class)->findById($uid);
        if($user['parent_id'] == 0){
            //主账号不验证
            return $builder->where('id',$uid)->orWhere('parent_id',$uid);
        }
        $mainUid = $user['parent_id'];
        $extInfo = $user['ext'];

        $dataScope = $extInfo['data_scope'] ?? 0;
        switch ($dataScope){
            case ChRoleDataScopeTypeConstants::SELF:
                $builder->where('id',$uid);
                break;
            case ChRoleDataScopeTypeConstants::ALL_SUB_ACCOUNT:
                $builder->where('parent_id',$mainUid);
                break;
            case ChRoleDataScopeTypeConstants::CUSTOM_DATA_SCOPE:
                $groupIds = explode(',',$extInfo['data_scope_extra']);
                $builder->whereIn('group_id',$groupIds);
                break;
        }

        $dataScopeAllow = $extInfo['data_scope_allow'] ?? 0;
        if($dataScopeAllow == 1){
            $builder->orWhere(function ($query) use ($mainUid,$tableName){
                $query->where('id',$mainUid);
            });
        }
        return $builder;
    }
}